package com.mingle.iwalk;

import java.io.File;
import java.util.List;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.location.Location;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.ViewAnimator;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class mainActivity extends Activity {
    
	private ListView mPOIsList;
	private ListView mTracksList;
	private TravelerInfoCursorAdapter mPOIsAdapter;
	private TravelerInfoCursorAdapter mTracksAdapter;
	private ViewAnimator mViewSwitcher;
	
	private Button mExitBtn;
	private Button mNewBtn;
	private RadioGroup mTpyeChooser;
	
	private Animation mRight2LeftInAnimation;
	private Animation mRight2LeftOutAnimation;
	private Animation mLeft2RightInAnimation;
	private Animation mLeft2RightOutAnimation;

	private ITrackService mService = null;
	private ServiceConnection osc = new ServiceConnection() {

		public void onServiceConnected(ComponentName name, IBinder binder) {
			mService = ITrackService.Stub.asInterface(binder);
			loadTravelInfo();

		}

		public void onServiceDisconnected(ComponentName name) {
			mService = null;
			
		}
	
	 };
	 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        mViewSwitcher =(ViewAnimator) findViewById(R.id.content_switcher);
        CompoundButton poiButtton =(CompoundButton) findViewById(R.id.pois);
        CompoundButton tracksButton =(CompoundButton) findViewById(R.id.tracks);
        poiButtton.setOnCheckedChangeListener(mOnCheckChangedListener);
        tracksButton.setOnCheckedChangeListener(mOnCheckChangedListener);
        
        mExitBtn = (Button) findViewById(R.id.exit_btn);
        mNewBtn  = (Button) findViewById(R.id.new_btn);
        mExitBtn.setOnClickListener(mOnBtnClickListener);
        mNewBtn.setOnClickListener(mOnBtnClickListener);
        mTpyeChooser = (RadioGroup) findViewById(R.id.type_chooser);
        
        mPOIsList =(ListView) findViewById(R.id.pois_list);
        mTracksList =(ListView) findViewById(R.id.tracks_list);
        
        mRight2LeftInAnimation = AnimationUtils.loadAnimation(getContext(),R.anim.slide_left_to_right_in);
        mRight2LeftOutAnimation = AnimationUtils.loadAnimation(getContext(),R.anim.slide_left_to_right_out); 
        mLeft2RightInAnimation = AnimationUtils.loadAnimation(getContext(),R.anim.slide_right_to_left_in);
        mLeft2RightOutAnimation = AnimationUtils.loadAnimation(getContext(),R.anim.slide_right_to_left_out);
        

        File dir= new File(TravelerConfig.APP_DATA_FOLDER);
		if(!dir.exists())
    	{
			dir.mkdirs();
    	}
		
		Intent serviceIntent = new Intent(getContext(), TrackService.class);
    	startService(serviceIntent);
		bindService((new Intent()).setClass(getContext(),TrackService.class), osc, 0);
    }
    
    private void loadTravelInfo()
    {
    	Cursor poiCursor = TravelerDB.getInstance(getContext()).getTravelerInfos(TravelerInfo.INFO_TYPE_POI);
    	mPOIsAdapter = new TravelerInfoCursorAdapter(getContext(), mService, R.layout.poi_item, R.layout.track_item, poiCursor, true);
    	mPOIsList.setAdapter(mPOIsAdapter);
    	mPOIsList.setOnItemClickListener(mPOIsContentListClickListener);
    	
    	Cursor trackCursor = TravelerDB.getInstance(getContext()).getTravelerInfos(TravelerInfo.INFO_TYPE_TRACK);
    	mTracksAdapter = new TravelerInfoCursorAdapter(getContext(), mService, R.layout.poi_item, R.layout.track_item, trackCursor, true);
    	mTracksList.setAdapter(mTracksAdapter);
    	mTracksList.setOnItemClickListener(mTracksContentListClickListener);
    }
    
    private OnCheckedChangeListener mOnCheckChangedListener = new OnCheckedChangeListener()
    {

		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			
			if(!isChecked)
			{
				return;
			}
			switch(buttonView.getId())
			{
			case R.id.pois:
				{
					mViewSwitcher.setDisplayedChild(0);
					mViewSwitcher.setOutAnimation(mLeft2RightOutAnimation);
					mViewSwitcher.setInAnimation(mLeft2RightInAnimation);
					mNewBtn.setText(R.string.create);
				}
				break;
				
			case R.id.tracks:
				{
					mViewSwitcher.setDisplayedChild(1);
					mViewSwitcher.setOutAnimation(mRight2LeftOutAnimation);
					mViewSwitcher.setInAnimation(mRight2LeftInAnimation);
					updateTrackNewBtn();
				}
				break;
			}
			
		}
    	
    };
    
    private OnClickListener mOnBtnClickListener = new OnClickListener()
    {

		@Override
		public void onClick(View v) {
			switch(v.getId())
			{
			case R.id.exit_btn:
			{
				finish();
			}
			break;
			
			case R.id.new_btn:
			{
				switch(mTpyeChooser.getCheckedRadioButtonId())
				{
				case R.id.pois:
				{
					Intent i = new Intent(getContext(), POIActivity.class);
					startActivity(i);
				}
				break;
				
				case R.id.tracks:
				{
					try {
						if(mService.getTrackServiceState() == TrackService.TRACK_SERVICE_STATUS_IDLE)
						{
							Intent i = new Intent(getContext(), TrackActivity.class);
							startActivity(i);
						}
						else
						{
							int id = mService.getTrackId();
							List<Location> list = mService.getTrackList();
							mService.stopRecord();
							TravelerDB db = TravelerDB.getInstance(getContext());
							db.saveTrackCount(id, (list!=null?list.size():0));
							
							mTracksAdapter.notifyDataSetChanged();
							mNewBtn.setText(R.string.create);
						}
					} catch (RemoteException e) {
						e.printStackTrace();
					}
				}
				break;
				}
			}
			break;
			
			}
			
		}
    	
    };
    
    private OnItemClickListener mPOIsContentListClickListener = new OnItemClickListener()
    {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int pos,
				long id) {
			Cursor c = (Cursor)mPOIsAdapter.getItem(pos);
			int infoId = c.getInt(c.getColumnIndex(TravelerDB._ID));
			int type = c.getInt(c.getColumnIndex(TravelerDB.TYPE));
			
			if(type == TravelerInfo.INFO_TYPE_POI)
			{
				Intent i = new Intent(getContext(), POIActivity.class);
				i.putExtra("INFO_ID", infoId);
				startActivity(i);
			}
			
			
		}
    	
    };
    
    private OnItemClickListener mTracksContentListClickListener = new OnItemClickListener()
    {

		@Override
		public void onItemClick(AdapterView<?> parent, View v, int pos,
				long id) {
			Cursor c = (Cursor)mTracksAdapter.getItem(pos);
			int infoId = c.getInt(c.getColumnIndex(TravelerDB._ID));
			int type = c.getInt(c.getColumnIndex(TravelerDB.TYPE));
			
			if(type == TravelerInfo.INFO_TYPE_TRACK)
			{
				Intent i = new Intent(getContext(), TrackActivity.class);
				i.putExtra("INFO_ID", infoId);
				startActivity(i);
			}
			
		}
    	
    };
    
    private void updateTrackNewBtn()
    {
    	if(mService == null)
    	{
    		mNewBtn.setText(R.string.create);
    		return;
    	}
    	
    	try {
			if(mService.getTrackServiceState() == TrackService.TRACK_SERVICE_STATUS_IDLE)
			{
				mNewBtn.setText(R.string.create);
			}
			else
			{
				mNewBtn.setText(R.string.stop_record);
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		}
    }
    
    private Context getContext()
    {
    	return mainActivity.this;
    }

	@Override
	protected void onResume() {
		if(mPOIsAdapter!=null)
		{
			mPOIsAdapter.getCursor().requery();
		}
		if(mTracksAdapter!=null)
		{
			mTracksAdapter.getCursor().requery();
		}
		
		if(mTpyeChooser.getCheckedRadioButtonId() == R.id.tracks)
		{
			updateTrackNewBtn();
		}
		
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		
		try {
			if(mService.getTrackServiceState() == TrackService.TRACK_SERVICE_STATUS_IDLE)
			{
				Intent serviceIntent = new Intent(getContext(), TrackService.class);
				stopService(serviceIntent);
			}
		} catch (RemoteException e) {
			
			e.printStackTrace();
		}
    	
    	unbindService(osc);
    	
		super.onDestroy();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(R.string.settings);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Intent i = new Intent(getContext(), SettingsActivity.class);
		startActivity(i);
		return super.onOptionsItemSelected(item);
	}
	
}